import gradio as gr
import time
import threading


class WeChatAutomation:
    def __init__(self):
        self.is_running = False
        self.log_messages = []

    def start_automation(
        self,
        target_wxid,
        keywords,
        send_limit,
        listen_time,
        filter_keywords,
        enable_filter,
        interval_minutes,
        min_amount,
        max_amount,
        send_wxid,
    ):
        self.is_running = True
        self.log_messages = []

        # 模拟自动化开始
        self.add_log(f"启动微信自动化，目标微信ID: {target_wxid}")
        self.add_log(f"关键词采集: {keywords}")
        self.add_log(f"每次最多发送: {send_limit} 条")
        self.add_log(f"监听时间段: {listen_time}")

        if enable_filter:
            self.add_log(f"已启用过滤，关键词: {filter_keywords}")

        self.add_log(f"发送间隔: {interval_minutes} 分钟")
        self.add_log(f"过滤金额: {min_amount}-{max_amount}")

        return "自动化已启动", "\n".join(self.log_messages)

    def stop_automation(self):
        self.is_running = False
        self.add_log("自动化已停止")
        return "自动化已停止", "\n".join(self.log_messages)

    def add_log(self, message):
        timestamp = time.strftime("%H:%M:%S")
        log_entry = f"{timestamp} {message}"
        self.log_messages.append(log_entry)
        if len(self.log_messages) > 100:  # 限制日志条数
            self.log_messages.pop(0)

    def get_current_log(self):
        return "\n".join(self.log_messages)


# 创建自动化实例
automation = WeChatAutomation()


# 创建Gradio界面
def create_interface():
    with gr.Blocks(title="微信自动化工具") as demo:
        gr.Markdown("# 微信自动化工具")

        with gr.Row():
            # 左侧控制面板
            with gr.Column(scale=2):
                gr.Markdown("## 控制面板")

                with gr.Group():
                    gr.Markdown("### 基础设置")
                    start_btn = gr.Button("启动微信", variant="primary")

                    target_wxid = gr.Textbox(
                        label="当前选择的对象",
                        value="wxid_b9zyb5tbbolm",
                        placeholder="输入目标微信ID",
                    )

                    send_limit = gr.Number(
                        label="每次最多发几条", value=45, precision=0
                    )

                with gr.Group():
                    gr.Markdown("### 关键词设置")
                    keywords = gr.Textbox(
                        label="采集关键词",
                        value="农业|广发",
                        placeholder="支持正则表达式",
                    )

                    listen_time = gr.Textbox(
                        label="监听时间段",
                        value="09:00:00-10:00:00",
                        placeholder="格式: HH:MM:SS-HH:MM:SS",
                    )

                with gr.Group():
                    gr.Markdown("### 过滤设置")
                    filter_keywords = gr.Textbox(
                        label="全额词是逻辑",
                        placeholder="手机 | 手机银行 | 专精特新 | 高新 | 保险 | 企业 | 阳光 | 不良 | 债务",
                    )

                    enable_filter = gr.Checkbox(label="开始监听", value=False)

                    interval_minutes = gr.Number(label="间隔分钟", value=5, precision=0)

                with gr.Group():
                    gr.Markdown("### 金额过滤")
                    with gr.Row():
                        min_amount = gr.Number(label="最小金额", value=48, precision=0)
                        max_amount = gr.Number(label="最大金额", value=290, precision=0)

            # 中间区域 - 接收和发送配置
            with gr.Column(scale=2):
                gr.Markdown("## 接收配置")

                with gr.Group():
                    gr.Markdown("### 接收微信ID")
                    receive_wxid = gr.Textbox(
                        label="接收微信ID",
                        value="wxid_b9zyb5tbbolm",
                        placeholder="输入接收微信ID",
                    )

                    # 模拟微信ID列表
                    receive_list = gr.Textbox(
                        label="微信ID列表",
                        value="""53386823720@chatroom——北
50440693440@chatroom——哈
34687976394@chatroom——上
44978394320@chatroom——中
39286185681@chatroom——深
34448906370@chatroom——哈
55914083934@chatroom——[@
39147612025@chatroom——RT
48769864705@chatroom——白
49040088182@chatroom——紫
59317022279@chatroom——紫
50203651818@chatroom——千
48519777467@chatroom——大
53757306260@chatroom——千
50112455607@chatroom——哈
45328185344@chatroom——圣
53115690907@chatroom——C""",
                        lines=10,
                        max_lines=15,
                    )

                gr.Markdown("## 发送配置")
                with gr.Group():
                    send_wxid = gr.Textbox(
                        label="发送微信ID",
                        value="wxid_b9zyb5tbbolm",
                        placeholder="输入发送微信ID",
                    )

                send_content = gr.Textbox(
                    label="发送内容", lines=3, placeholder="输入要发送的内容"
                )
                # 发送内容按钮
                send_content_btn = gr.Button("发送内容")

            # 右侧日志区域
            with gr.Column(scale=2):
                gr.Markdown("## 运行日志")

                status_display = gr.Textbox(
                    label="状态", value="未启动", interactive=False
                )

                log_display = gr.Textbox(
                    label="日志输出", lines=20, max_lines=25, interactive=False
                )

                with gr.Row():
                    stop_btn = gr.Button("停止", variant="stop")
                    clear_log_btn = gr.Button("清空日志")
                    refresh_log_btn = gr.Button("刷新日志")

        # 事件绑定函数
        def start_automation_handler(*args):
            return automation.start_automation(*args)

        def stop_automation_handler():
            return automation.stop_automation()

        def clear_log():
            automation.log_messages = []
            return "未启动", ""

        def refresh_log():
            return automation.get_current_log()

        def send_message(content, wxid):
            if content.strip():
                automation.add_log(f"发送消息到 {wxid}: {content[:50]}...")
                return automation.get_current_log(), ""
            return automation.get_current_log(), content

        # 绑定按钮事件
        start_btn.click(
            fn=start_automation_handler,
            inputs=[
                target_wxid,
                keywords,
                send_limit,
                listen_time,
                filter_keywords,
                enable_filter,
                interval_minutes,
                min_amount,
                max_amount,
                send_wxid,
            ],
            outputs=[status_display, log_display],
        )

        stop_btn.click(
            fn=stop_automation_handler, outputs=[status_display, log_display]
        )

        clear_log_btn.click(fn=clear_log, outputs=[status_display, log_display])

        refresh_log_btn.click(fn=refresh_log, outputs=[log_display])

        send_content_btn.click(
            fn=send_message,
            inputs=[send_content, send_wxid],
            outputs=[log_display, send_content],
        )

    return demo


# 启动应用
if __name__ == "__main__":
    demo = create_interface()
    demo.launch(server_name="0.0.0.0", server_port=7860, share=False, debug=True)
